<template>
    <div class="login zw-img-bg">
        <div class="login-panel">
            <div class="title">客易达商城管理系统</div>
            <el-tabs v-model="currentTab" @tab-click="changeTabHandler">
                <el-tab-pane label="账号密码登录" :name="1"></el-tab-pane>
                <el-tab-pane label="手机号登录" :name="2"></el-tab-pane>
            </el-tabs>
            <el-form
                :model="loginForm"
                :rules="loginFormRules"
                ref="loginFormRef"
                label-width="0"
                class="login-form"
                size="large"
                v-if="currentTab === 1">
                <el-form-item label="" prop="mobile">
                    <el-input v-model.trim="loginForm.mobile" placeholder="手机号" ref="loginFormMobileRef"></el-input>
                </el-form-item>
                <!-- <el-form-item label="" prop="password">
                    <el-input type="password" v-model="loginloginForm.password" show-password placeholder="密码"></el-input>
                </el-form-item> -->
                <el-form-item prop="password">
                    <el-input
                        :key="passwordType"
                        ref="passwordRef"
                        v-model.trim="loginForm.password"
                        :type="passwordType"
                        maxlength="16"
                        placeholder="密码"
                        @keyup.enter="loginHandler" />
                    <span v-if="passwordType === 'password'" class="show-password" @click="handlePassword">
                        <el-icon><Hide /></el-icon>
                    </span>
                    <span v-else class="show-password" @click="handlePassword">
                        <el-icon><View /></el-icon>
                    </span>
                </el-form-item>
                <el-form-item label="" prop="remind" class="remind">
                    <div class="pwd-area">
                        <span></span>
                        <el-button type="primary" class="btn" text @click="findpwdHandler">忘记密码</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <el-form
                :model="loginSmsForm"
                :rules="loginSmsFormRules"
                ref="loginSmsFormRef"
                label-width="0"
                class="login-form"
                size="large"
                v-if="currentTab === 2">
                <el-form-item label="" prop="mobile">
                    <el-input v-model.trim="loginSmsForm.mobile" placeholder="手机号" ref="loginSmsFormMobileRef">
                    </el-input>
                </el-form-item>
                <el-form-item label="">
                    <SmsCode v-model.trim="loginSmsForm.smsCode" :mobile="loginSmsForm.mobile" from="login" />
                </el-form-item>
                <el-form-item label="" prop="remind" class="remind">
                    <div class="pwd-area">
                        <span></span>
                        <el-button class="btn" type="primary" text @click="findpwdHandler">忘记密码</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <el-form class="login-form">
                <el-form-item>
                    <el-button
                        type="primary"
                        :disabled="isDisabled"
                        size="large"
                        class="login-submit"
                        @click="loginHandler">
                        登 录
                    </el-button>
                    <div class="register">
                        <span class="no-accout">没有账户？</span>
                        <el-button type="primary" class="register-btn" text @click="registHandler">立即注册</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive, ref, inject, onMounted, nextTick } from 'vue';
import request from '@/request';
import SmsCode from '@/components/SmsCode.vue';
import storage from '@/commons/storage';
import { useRouter } from 'vue-router';
import { isMobile, isPassword } from '@/commons/utils';

const bus = inject('bus');
const router = useRouter();
const loginFormRef = ref(null);
const loginSmsFormRef = ref(null);
const loginFormMobileRef = ref(null);
const loginSmsFormMobileRef = ref(null);
let currentTab = ref(1);

const loginForm = reactive({
    mobile: '',
    password: ''
});

const loginSmsForm = reactive({
    mobile: '',
    smsCode: ''
});

/**
 * 密码规则校验
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePasswordRule = (rule, value, callback) => {
    if (isPassword(value)) {
        callback();
    } else {
        callback(new Error('长度8-16个字符，由数字或字母组成且不能有特殊字符'));
    }
};

const validatePhone = (rule, value, callback) => {
    if (isMobile(value)) {
        callback();
    } else {
        callback(new Error('请输入正确的手机号!'));
    }
};

const loginFormRules = reactive({
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePasswordRule, trigger: 'blur' }
    ]
});

const loginSmsFormRules = reactive({
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
    ],
    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
});

bus.off('sendSms:login');
bus.on('sendSms:login', () => {
    setTimeout(() => {
        loginSmsFormRef.value.validateField('mobile');
    }, 0);
});

const isDisabled = computed(() => {
    if (currentTab.value === 1) {
        const { mobile, password } = loginForm;
        return !mobile || !password;
    } else {
        const { mobile, smsCode } = loginSmsForm;
        return !mobile || !smsCode;
    }
});

/**
 * 切换登录方式
 * @param tab
 */
const changeTabHandler = tab => {
    currentTab.value = tab.paneName;
};

/**
 * 用户名登录
 */
const loginFormHandler = () => {
    loginFormRef.value.validate(async valid => {
        if (valid) {
            const res = await request('loginServ', loginForm);
            loginAfterHandler(res);
        }
    });
};

/**
 * 手机号登录
 */
const loginSmsFormHandler = () => {
    loginSmsFormRef.value.validate(async valid => {
        if (valid) {
            const res = await request('loginSmsServ', loginSmsForm);
            loginAfterHandler(res);
        }
    });
};

/**
 * 缓存登录态并跳转
 * @param {*} res
 */
const loginAfterHandler = res => {
    const { token, username } = res.data;
    storage.set('ZW-TOKEN', token);
    storage.set('ZW-USER', { username });
    router.replace('/company');
};

/**
 * 执行登录
 */
const loginHandler = async () => {
    currentTab.value === 1 ? loginFormHandler() : loginSmsFormHandler();
};

/**
 * 忘记密码
 */
const findpwdHandler = () => {
    router.push('/findpwd');
};

/**
 * 去注册
 */
const registHandler = () => {
    router.push('/regist');
};
/**
 * 密码可见
 */
const passwordRef = ref(null);
const passwordType = ref('password');
const handlePassword = () => {
    passwordType.value === 'password' ? (passwordType.value = '') : (passwordType.value = 'password');
    nextTick(() => {
        passwordRef.value.focus();
    });
};
</script>
<style lang="scss" src="./style.scss" scoped></style>
